import traceback
from datetime import datetime
from langgraph.checkpoint import MemorySaver
from langgraph.constants import END
from langgraph.graph import StateGraph

from domain.mapper.spider_task import SpiderTask
from graph.nodes import shopee_spider_node, remove_watermark_node, add_watermark_node, \
    extract_info, listing_change, archive_node, broswerless_express_node
from graph.states import EshopAssistantState

class EshopAssistantGraph:
    """
    商品上架流程:
    每天运行一次（具体时间待定）：
    爬取物料信息存minio基本信息存mysql
    1、爬速卖通最新商品信息（diff）
    2、爬虾皮最新商品信息（diff）
    3、获取指定各种品牌的手机做最新型号的新闻获取，获取到手机型号后，对速卖通与虾皮进行手机型号+商品类型进行搜索，然后进行爬取，ps：获取最新手机信息是同时需要爬取手机原图（diff）ps:暂时不做
    4、对爬取取所有图片进行去水印操作
    5、对爬取的所有图片进行加水印操作
    6、对爬取的所有图片进行图片分类（主要对爬取的新手机的原图进行分类，对图片中手机展现的方式，例如正面图，侧面图等进行分类）ps：暂时不做
    7、对所有的des与specification对描述模板的关键字信息做提取
    8、对所有listing做变形
    9、数据归档
    """

    graph_server = StateGraph(EshopAssistantState)
    memory = MemorySaver()

    graph_server.add_node("express_spider",broswerless_express_node)
    #graph_server.add_node("shopee_spider", shopee_spider_node)
    graph_server.add_node("remove_watermark", remove_watermark_node)
    graph_server.add_node("add_watermark", add_watermark_node)
    graph_server.add_node("extert_description", extract_info)
    graph_server.add_node("archive", archive_node)
    #graph_server.add_node("listing_change", listing_change)

    graph_server.set_entry_point("express_spider")
    #graph_server.add_edge("express_spider", "shopee_spider")
    #graph_server.add_edge("shopee_spider", "remove_watermark")
    graph_server.add_edge("express_spider", "remove_watermark")
    graph_server.add_edge("remove_watermark", "add_watermark")
    graph_server.add_edge("add_watermark", "extert_description")
    graph_server.add_edge("extert_description", "archive")
    graph_server.add_edge("archive", END)
    graph = graph_server.compile(debug=True, checkpointer=memory)

    @staticmethod
    def start_graph(task_id, run_info, work_dir, user_id):
        try:
            EshopAssistantGraph.graph.invoke({"product_path":[], "task_info":[]}, {"configurable": {"thread_id": task_id}, 'run_info' : run_info, "work_dir":work_dir, "user_id":user_id})
        except Exception as e:
            print(f"{task_id}失败，失败原因：{e}")
            traceback.print_exc()
            SpiderTask.update_param_by_id(task_id=task_id, update_param={"task_state":"失败", "task_info":str(traceback.format_exc()), 'finish_time':datetime.now()})
        finally:
            work_dir[1] = False


